#![allow(non_snake_case)]

use std::collections::HashMap;

use crate::components::CommonPage;
use crate::components::{ButtonList, DataRange};
use crate::zhzjfp::{zxjl_fp_insert, zxjl_fpjg};
use icondata as i;
use leptos::{prelude::*, task::spawn_local};
use leptos_icons::*;
use serde_json::{Map, Value};
use shq_common::prelude::options::FetchParams;
use shq_common::prelude::Size;
use shq_web_controls::{
    use_message, AutoSearch, Input, InputNumber, MessageOptions, MessageVariant, MonthPicker,
    Select, ToastPosition, ToasterProvider,
};
use thaw_utils::ArcOneCallback;

#[component]
pub fn ZhzjFp(menu_id: u32) -> impl IntoView {
    let display_import: RwSignal<bool> = RwSignal::new(false);
    let yf: RwSignal<i32> = RwSignal::new(i32::default());
    let on_tolbar_params_change = ArcOneCallback::new(move |params: HashMap<String, String>| {
        if let Some(yf_str) = params.get("ny") {
            if let Ok(yf_str) = yf_str.parse::<i32>() {
                yf.set(yf_str);
            }
        }
    });

    let cgid_value: RwSignal<i32> = RwSignal::new(i32::default());
    let jle_value = RwSignal::new(String::new());
    let jlmc = RwSignal::new(None::<String>);
    let options = Resource::new(
        move || (),
        |_| async { crate::zhzjfp::zxjl_conf_zb().await },
    );
    let fpe_value = RwSignal::new(None::<String>);
    let syed_value = RwSignal::new(f64::default());
    let zfpje_value: RwSignal<Value> = RwSignal::new(Value::Null);
    let ffyf = RwSignal::new(None::<i32>);
    let emid = RwSignal::new(None::<i32>);
    let emnm = RwSignal::new(String::new());
    let zbid = RwSignal::new(None::<i32>);
    let saving = RwSignal::new(false);
    let mess = use_message();
    let is_fp = RwSignal::new(false);

    let custom_button_fp_callback = ArcOneCallback::new(move |_| {
        if jle_value.get().is_empty() {
            // 显示错误提示
            mess.create(
                "请先选择分类",
                MessageVariant::Error,
                MessageOptions::default(),
            );
        } else {
            // 已选择则打开窗口
            display_import.set(true);
        }
    });

    let on_row_select_change =
        ArcOneCallback::new(move |selected_rows: Option<Map<String, Value>>| {
            if let Some(rows) = selected_rows {
                if let Some(Value::Number(cgid)) = rows.get("cgid") {
                    if let Some(cgid1) = cgid.as_i64().map(|x| x as i32) {
                        cgid_value.set(cgid1);
                    }
                }
                if let Some(Value::String(jlmc1)) = rows.get("cgid__dict") {
                    jlmc.set(Some(jlmc1.to_string()));
                }
                if let Some(Value::Number(jle)) = rows.get("jle") {
                    if let Some(jle1) = jle.as_f64() {
                        jle_value.set(jle1.to_string());
                    }
                }
                if let Some(Value::Number(fpe)) = rows.get("fpe") {
                    if let Some(fpe1) = fpe.as_f64() {
                        fpe_value.set(Some(fpe1.to_string()));
                    }
                }
                if let Some(Value::Number(syed)) = rows.get("syed") {
                    if let Some(syed1) = syed.as_f64() {
                        syed_value.set(syed1);
                    }
                }
                if let Some(Value::Number(zfpje)) = rows.get("zfpje") {
                    if let Some(zfpje1) = zfpje.as_f64() {
                        zfpje_value.set(zfpje1.into());
                    }
                }
            }
        });
    let on_change_jlmc = move |value: Option<String>| {
        jlmc.set(value);
    };

    let on_change_fpe = move |value: Option<f64>| {
        fpe_value.set(value.map(|v| v.to_string()));
    };

    let on_change_ffyf = move |value: Option<i32>| {
        if let Some(v) = value {
            ffyf.set(Some(v));
        } else {
            ffyf.set(None);
        }
    };

    let on_change_tx = move |value: Option<String>| {
        if let Some(v) = value {
            if let Ok(int_emid) = v.parse::<i32>() {
                zbid.set(Some(int_emid));
            } else {
                zbid.set(None); // 或者其他的默认值
            }
        } else {
            zbid.set(None); // 或者其他默认值
        }
    };

    let fp_tx = move || match options.get() {
        Some(Ok(opt)) => Some(view! {
            <Select options=opt.clone() can_filter=true size=Size::SM  on_change=on_change_tx value=zbid.get().map(|v| v.to_string()) />
        }),
        Some(Err(e)) => {
            log::error!("无法获取条线: {}", e);
            None
        }
        None => {
            log::warn!("条线未设置");
            None
        }
    };

    let on_change_user = move |value: Option<String>| {
        if let Some(v) = value {
            if let Ok(int_emid) = v.parse::<i32>() {
                emid.set(Some(int_emid));
            } else {
                emid.set(None); // 或者其他的默认值
            }
        } else {
            emid.set(None); // 或者其他默认值
        }
    };
    let save_fp_info = Action::new(move |_| {
        let yf_val = yf.get();
        let cgid_val = cgid_value.get();
        let fp_val = fpe_value
            .get()
            .unwrap_or(String::from("0.0"))
            .parse::<f64>()
            .unwrap();
        let emid_val = emid.get().unwrap_or(0);
        let zbid_val = zbid.get().unwrap_or(0);
        let jlmc_val = jlmc.get().unwrap_or_default();
        let ffyf_val = ffyf.get().unwrap_or(0);
        async move {
            saving.set(true);
            if fp_val <= 0.0 {
                mess.create(
                    "分配限额必须大于0",
                    MessageVariant::Error,
                    MessageOptions::default(),
                );
                return;
            }

            if fp_val > jle_value.get().parse::<f64>().unwrap() {
                mess.create(
                    "分配限额不能超过奖励额",
                    MessageVariant::Error,
                    MessageOptions::default(),
                );
                saving.set(false);
                return;
            }

            if zbid_val == 0 {
                mess.create(
                    "请选择条线",
                    MessageVariant::Error,
                    MessageOptions::default(),
                );
                saving.set(false);
                return;
            }
            if emid_val == 0 {
                mess.create(
                    "请选择分配人",
                    MessageVariant::Error,
                    MessageOptions::default(),
                );
                saving.set(false);
                return;
            }
            match zxjl_fp_insert(
                yf_val, cgid_val, fp_val, emid_val, ffyf_val, jlmc_val, zbid_val,
            )
            .await
            {
                Ok(_) => {
                    mess.create(
                        "分配成功",
                        MessageVariant::Success,
                        MessageOptions::default(),
                    );
                    display_import.set(false);
                    yf.set(yf.get());
                    is_fp.set(true);
                }
                Err(e) => {
                    mess.create(
                        format!("分配失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default(),
                    );
                    saving.set(false);
                }
            }
        }
    });

    //监听ID变化，动态加载对应分析报告
    Effect::new(move |prev_id| {
        let current_id = cgid_value.get();
        if prev_id == Some(current_id) {
            return current_id;
        }

        spawn_local(async move {
            match zxjl_fpjg(current_id).await {
                Ok(report) => {
                    if let Some(first_report) = report.first() {
                        let new_jlmc = if first_report.zjmc.is_empty() {
                            jlmc.get()
                        } else {
                            Some(first_report.zjmc.clone())
                        };
                        jlmc.set(new_jlmc);
                        fpe_value.set(Some(first_report.fpje.to_string()));
                        ffyf.set(Some(first_report.ffny));
                        zbid.set(Some(first_report.txid.clone()));
                        emid.set(Some(first_report.fpr_emid.clone()));
                        emnm.set(first_report.fpr_emnm.clone());
                    } else {
                        fpe_value.set(None);
                        ffyf.set(None);
                        zbid.set(None);
                        emid.set(None);
                        emnm.set(String::new());
                    }
                }
                Err(e) => {
                    mess.create(
                        format!("加载分析报告失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default(),
                    );
                    jlmc.set(None);
                    fpe_value.set(None);
                    ffyf.set(None);
                    zbid.set(None);
                    emid.set(None);
                    emnm.set(String::new());
                }
            }
        });

        current_id
    });
    let fp_view = move || {
        if display_import.get() {
            Some(view! {
                <dialog id="data_import_modal" class="modal modal-open z-50">
                    <div class="modal-box overflow-hidden max-w-2xl p-6" >
                        <div class="flex items-center justify-center mb-6 relative">
                            <h3 class="font-bold text-lg">专项奖励分配</h3>
                            <button class="absolute right-2 top-0" on:click=move|_|{
                            display_import.set(false);
                             }>
                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                           </button>
                        </div>
                        <div class="space-y-4">
                            <div class="flex items-center gap-3">
                                <h2 class="text-lg font-bold">奖励额:</h2>
                                <span class="text-lg font-bold">{jle_value.get()}</span>
                            </div>
                            <div class="flex items-center gap-3">
                                <h2 class="text-lg font-bold">奖励名称:</h2>
                                <Input
                                    placeholder="请输入奖励名称"
                                    size=Size::SM
                                    inner_max_width=200
                                    on_change=on_change_jlmc
                                    value = jlmc
                                />
                            </div>
                            <div class="flex items-center gap-3">
                                <h2 class="text-lg font-bold">分配限额:</h2>
                                // <Input
                                //     placeholder="请输入分配限额"
                                //     size=Size::SM
                                //     inner_max_width=200
                                //     on_change=on_change_fpe
                                //     value = fpe_value
                                // />
                                <InputNumber
                                    step =  0.1
                                    value = fpe_value.get().and_then(|v| v.parse::<f64>().ok())
                                    placeholder="请输入分配限额"
                                    size=Size::SM
                                    inner_max_width=200
                                    on_change = on_change_fpe
                                />
                            </div>
                            <div class="flex items-center gap-3">
                                <h2 class="text-lg font-bold">发放月份:</h2>
                                <MonthPicker
                                    placeholder="请选择发放月份"
                                    size=Size::SM
                                    inner_max_width=200
                                    on_change=on_change_ffyf
                                    value = ffyf
                                />
                            </div>
                            <div class="flex items-center gap-3">
                                <h2 class="text-lg font-bold">分配条线:</h2>
                                {fp_tx()}
                            </div>
                            <div class="flex items-center gap-3">
                                <h2 class="text-lg font-bold">分配人:</h2>
                                <AutoSearch
                                    label=""
                                    value=Some(emnm.get())
                                    size=Size::SM
                                    fetch_params=StoredValue::new(FetchParams {
                                        table_name: "v_user_name".to_string(),
                                        label_col: "name".to_string(),
                                        value_col: "id".to_string(),
                                        parent_col: None,
                                        where_cause: Some("name".to_string()),
                                        order_by: Some("id".to_string()),
                                        search_cols: Some(vec!["name".to_string()]),
                                    })
                                    on_change=on_change_user
                                    err_msg = " "
                                />
                            </div>
                        <div class="flex justify-end gap-2 mt-6 ">
                            <button class="btn btn-secondary px-6 py-3" on:click=move|_|{
                                display_import.set(false);}>取消</button>
                            <button class="btn btn-primary px-6 py-3"
                                    on:click=move|_| {
                                        save_fp_info.dispatch(());
                                    }>
                                确认
                            </button>
                        </div>
                    </div>
                </div>
                </dialog>
            })
        } else {
            None
        }
    };

    // 定义自定义按钮
    let custom_buttons = {
        let mut bl = ButtonList::new();
        bl.add_custom(
            "分配".to_string(),
            Some(i::AiAlignCenterOutlined),
            None,
            None,
            DataRange::None,
            Vec::new(),
            custom_button_fp_callback,
        );
        bl
    };

    view! {
        <div class="flex flex-1 gap-4 min-h-1 p-4 pb-2 w-full h-full  overflow-hidden">
            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                <CommonPage menu_id conf_name="zhzj_fp" custom_buttons on_row_select_change on_tolbar_params_change is_refresh=is_fp/>
            </Suspense>
             <ToasterProvider position=ToastPosition::TopStart>
                    {fp_view}
            </ToasterProvider>
        </div>
    }
}
